<?php

namespace app\admin\serivce;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;


class JwtAuth
{

    private static $key;

    /**
     * 把明文加密为字符串
     */
    public static function generate(array $data): string
    {
        self::$key = self::getKey();
        $secret = JWT::encode($data, self::$key, 'HS256');
        \think\facade\Cache::set('secret', $secret);
        return $secret;
    }

    /**
     * 解密出原文
     */
    public static function parse($secret): array
    {
        self::$key = self::getKey();

        // 结果为stdClass
        $original = JWT::decode($secret, new Key(self::$key, 'HS256'));

        // 转为json字符串
        $original = json_encode($original);
        // 转为数组
        return json_decode($original, true);
    }

    protected static function getKey()
    {
        return \think\facade\Config::get('custom.jwt_key');
    }
}
